package eerbaar.client.internal.ctr.operator;

import eerbaar.client.ctr.OperatorConstants;
import eerbaar.client.exp.ExpException;
import eerbaar.client.exp.IExp;
import eerbaar.client.exp.IScope;
import eerbaar.client.exp.IState;
import eerbaar.client.internal.ctr.operator.area.ValueArea;
import eerbaar.client.internal.ctr.operator.area.ValueAreaHelper;
import eerbaar.client.internal.ctr.operator.area.ValueAreaPopulator;
import eerbaar.game.IGame;
import eerbaar.persona.IPersona;
import eerbaar.position.IPosition;

class Add implements IExp {

    private final IExp[] array;

    public Add(IExp[] array) {
        this.array = array;
    }

    @Override
    public IPosition calcDestination(IScope scope) {

        ValueArea va = (ValueArea) scope.getValueArea();
        IGame game = (IGame) scope.getGame();
        if (va == null) {
            va = new ValueArea(game);
            scope.setValueArea(va);
        }
        ValueAreaPopulator populator = new ValueAreaPopulator(va, game,
                this.array);

        IPersona target = (IPersona) scope.getTarget();
        if (target.getName().equals("pet")) {
            ValueAreaHelper.setValueArea(va);
        }

        return populator.calcDestination(scope);
    }

    @Override
    public IScope interpret(IScope inScope) throws ExpException {

        IScope scope = inScope;

        IPersona pet = (IPersona) scope.getTarget();
        IGame game = (IGame) scope.getGame();

        this.populateValueArea(scope);
        IPosition destination = this.calcDestination(scope);

        IState state = scope.getState();
        if (destination == null) {

            state.setFinished(true);
        } else {

            IExp exp = Global.calcMoveTo(game, pet, pet.getPosition(),
                    destination);
            if (exp == null) {

                state.setFinished(true);
            } else {

                exp.interpret(scope);
                state.setFinished(false);
            }
        }

        return scope;
    }

    @Override
    public boolean isInteresting(String elementName) {

        return false;
    }

    @Override
    public void populateValueArea(IScope scope) {

        ValueArea va = (ValueArea) scope.getValueArea();
        IGame game = (IGame) scope.getGame();
        if (va == null) {
            va = new ValueArea(game);
            scope.setValueArea(va);

            ValueAreaHelper.setValueArea(va);
        }
        ValueAreaPopulator populator = new ValueAreaPopulator(va, game,
                this.array);
        populator.populateValueArea(scope);
    }

    @Override
    public String toString() {

        String s = "";
        for (IExp e : this.array) {
            s += e.toString();
        }

        return OperatorConstants.ADD + "(" + s + ")";
    }

    @Override
    public void updateArea(IScope scope) {
        //
    }

}
